package cn.felord.common.security;

import cn.hutool.core.util.RandomUtil;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Dax
 * @since 23:57  2018/9/20
 */
public class JwtClaimsBuilder {

    //    jwt签发者
    private String iss;
    //jwt所面向的用户
    private String sub;
    // 接收jwt的一方
    private String userId;
    //jwt的过期时间，这个过期时间必须要大于签发时间
    private LocalDateTime exp;
    //jwt的签发时间
    private LocalDateTime iat = LocalDateTime.now();
    //jwt的唯一身份标识，主要用来作为一次性token,从而回避重放攻击
    private String jti = RandomUtil.simpleUUID();

    public JwtClaimsBuilder iss(String iss) {
        this.iss = iss;
        return this;
    }


    public JwtClaimsBuilder sub(String sub) {
        this.sub = sub;
        return this;
    }

    public JwtClaimsBuilder userId(String userId) {
        this.userId = userId;
        return this;
    }

    public JwtClaimsBuilder expDays(long days) {
        Assert.isTrue(days > 0, "expireDate must after now");
        this.exp = this.iat.plusDays(days);
        return this;
    }

    public JwtClaims builder() {
        JwtClaims jwtClaims = new JwtClaims();
        jwtClaims.setIss(this.iss);
        jwtClaims.setSub(this.sub);
        jwtClaims.setAud(this.userId);
        jwtClaims.setExp(this.exp.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        jwtClaims.setIat(this.iat.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        jwtClaims.setJti(this.jti);
        return jwtClaims;

    }
}
